package com.project.core.util;

import cn.hutool.core.util.StrUtil;
import com.project.core.constant.ScoreConstant;
import com.project.core.exception.ScoreException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;

/**
 * @author mengxj
 */
@Slf4j
public final class CommonUtil {

    /**
     * 私有构造器，外界不可创建
     */
    private CommonUtil(){}

    /**
     * 获取request对象
     * @return request对象
     */
    public static HttpServletRequest getRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return Objects.requireNonNull(request);
    }

    /**
     * 获取response对象
     * @return request对象
     */
    public static HttpServletResponse getResponse(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletResponse request = ((ServletRequestAttributes)requestAttributes).getResponse();
        return Objects.requireNonNull(request);
    }

    public static void throwException(String msg){
        throwException(msg, null);
    }

    public static void throwException(int code, String msg){
        throwException(code, msg, null);
    }

    public static void throwException(String msg, Throwable e){
        throwException(ScoreConstant.OPERATOR_ERROR_CODE, msg, e);
    }

    public static void throwException(Integer code, String msg, Throwable e){
        ScoreException ex = new ScoreException(code, msg);
        if(Objects.nonNull(e)){
            if(StrUtil.isEmpty(msg) && e instanceof ScoreException){
                ex = (ScoreException)e;
            }else{
                ex.addSuppressed(e);
            }
        }
        throw ex;
    }

    public static String getExceptionMessage(Throwable e){
        try (StringWriter sw = new StringWriter();
             PrintWriter pw = new PrintWriter(new BufferedWriter(sw))){
            e.printStackTrace(pw);
            pw.flush();
            return sw.getBuffer().toString();
        } catch (IOException ex) {
            log.error("获取错误信息失败");
        }
        return StrUtil.EMPTY;
    }
}
